// miniprogram/pages/usersList.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputId: '', //待查找的id
    showBottom: false, // 显示底部状态栏
    total: '', // 总用户数
    pageIndex: 1, // 当前页面数
    users: [], //用户数据汇总
    perPage: 10 //每页显示用户数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.setData({
      type: options.type,
      openid: options.openid
    })
    //获取用户总数
    this.getUsersCount()
    //获取用户信息
    this.getUserInfoByIndex(this.data.pageIndex)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.toggleBottomStatus(true)
    let users = this.data.users
    let total = this.data.total
    let index = this.data.pageIndex

    //如果不是尾页，则需要加载数据
    if (users.length < total) {
      this.getUserInfoByIndex(index + 1)
    }

  },
  toggleBottomStatus: function(bool) {
    this.setData({
      showBottom: bool
    })
  },
  //------------------------------------------获取用户总数
  getUsersCount: function() {
    let that = this
    let type =this.data.type
    let openid = this.data.openid
    let condition = type == 'recv' ? { recv_openid: openid} : {give_openid:openid}

    db.collection('activity_log').where(condition).count().then(res => {
      that.setData({
        total: res.total
      })
    })
  },
  //------------------------------------------根据页码获取用户信息
  getUserInfoByIndex: function(index) {
    let that = this
    let type = this.data.type
    let openid = this.data.openid
    let condition = type == 'recv' ? { recv_openid: openid } : { give_openid: openid }

    let limit = this.data.perPage
    let skip = limit * (index - 1)
    let users = this.data.users
    console.log('skip:', skip, 'limit:', limit, 'users:', users)
    db.collection('activity_log')
      .where(condition)
      .skip(skip) // 跳过结果集中的xx条
      .limit(limit) // 限制返回数量为xx条
      .get()
      .then(res => {
        console.log(res)
        for (let i = 0; i < res.data.length; i++) {
          users.push(res.data[i])
        }

        that.setData({
          users: users,
          pageIndex: index
        })
        that.toggleBottomStatus(false)
      })
  },
})